from PySide6.QtWidgets import (
    QGroupBox, QVBoxLayout, QPushButton,
    QTreeWidget, QTreeWidgetItem, QHeaderView
)
from PySide6.QtCore import Qt
from .base_module import BaseModule
from presenter.disk_presenter import DiskPresenter

class DiskModule(BaseModule):
    """磁盘检测模块"""

    def __init__(self, server_manager=None):
        super().__init__()  
        self.disk_pr = DiskPresenter(self, server_manager)
        self.init_connections()

    def init_ui(self):
        left_panel = QVBoxLayout()

        disk_group = QGroupBox("服务器磁盘信息")
        disk_layout = QVBoxLayout(disk_group)

        self.btn_check = QPushButton("查询磁盘容量")
        disk_layout.addWidget(self.btn_check)

        self.tree = QTreeWidget()
        self.tree.setHeaderLabels(["服务器", "分区", "总空间", "剩余空间", "使用率", "状态"])
        header = self.tree.header()

        header.setSectionResizeMode(0, QHeaderView.Fixed)
        self.tree.setColumnWidth(0, 200)
        for i in range(1, 6):
            header.setSectionResizeMode(i, QHeaderView.Stretch)

        disk_layout.addWidget(self.tree)
        left_panel.addWidget(disk_group)
        self.layout.addLayout(left_panel)

    def init_connections(self):
        """信号连接"""
        self.btn_check.clicked.connect(self.on_disk_check)
        self.disk_pr.disk_check_finished.connect(self.update_table)
        self.bus.log_message.connect(lambda msg: self.ToastWidget(self, msg))

    def on_disk_check(self):
        """点击按钮启动磁盘检测"""
        self.tree.clear()
        self.disk_pr.handle_disk_check()

    def update_table(self, results: dict):
        """更新表格显示"""
        print("[DEBUG] 收到磁盘检测结果:", results)

        self.tree.clear()
        stats = results.get("statistics", {})
        result_map = results.get("results", {})

        for ip, res in result_map.items():
            top = QTreeWidgetItem(self.tree)

            # ✅ 取字段时用 get，避免 NoneType 报错
            station = res.get("station", "Unknown")
            ip_addr = res.get("ip", "Unknown")
            top.setText(0, f"{station} ({ip_addr})" if station else ip_addr)

            # 离线状态
            if not res.get("connection_status"):
                top.setText(5, "❌ 离线")
                for i in range(6):
                    top.setForeground(i, Qt.red)
                continue

            disks = res.get("disks", [])
            if not disks:
                top.setText(1, "⚠️ 无数据")
                continue

            total = disks[0]
            top.setText(2, total.get("total", ""))
            top.setText(3, total.get("avail", ""))
            top.setText(4, total.get("use_percent", ""))
            top.setText(5, "✅ 充足" if total.get("is_sufficient") else "❌ 不足")

            if not total.get("is_sufficient"):
                for j in range(6):
                    top.setForeground(j, Qt.darkRed)

            # 子项：各个分区
            for d in disks[1:]:
                child = QTreeWidgetItem(top)
                child.setText(1, d.get("mountpoint", "-"))
                child.setText(2, d.get("total", ""))
                child.setText(3, d.get("avail", ""))
                child.setText(4, d.get("use_percent", ""))
                child.setText(5, "")
            # 默认折叠
            self.tree.collapseItem(top)
